<template>
    <span>
        <div class="demo-upload-list" v-for="item in uploadList">
            <template v-if="item.status === 'finished'">
                <img :src="item.url">
                <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                </div>
            </template>
            <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
        </div>
        <Upload
                v-show="isMany || !uploadList.length"
                ref="upload"
                :show-upload-list="false"
                :default-file-list="defaultList"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="maxSize"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                multiple
                type="drag"
                :action="uploadUrl"
                :headers="headers"
                :name="name"
                :data="data"
                style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
                <Icon type="ios-camera" size="20"></Icon>
            </div>
        </Upload>
        <Modal title="图片预览" v-model="visible">
            <img :src="bigImgUrl" v-if="visible" style="width: 100%">
        </Modal>
    </span>
</template>
<script>
    export default {
        name   : 'uploadImg',
        data() {
            return {
                defaultList: [],
                bigImgUrl  : '',
                visible    : false,
                uploadList : [],
            }
        },
        props  : {
            isMany   : {//是否传多张
                type   : Boolean,
                default: false,
            },
            uploadUrl: {//上传地址
                type   : String,
                default: '',
            },
            headers  : {//额外上传头部
                type   : Object,
                default: () => {},
            },
            maxSize  : {//文件大小限制
                type   : Number,
                default: 2048,
            },
            isOnlyUrl: {//是否值返回url地址
                type   : Boolean,
                default: true,
            },
            name: {//上传字段名称
                type   : String,
                default: 'img',
            },
            data: {//上传时附带的额外参数
                type   : Object,
                default: () => {},
            },
            value: {
                validator: function (value) {
                    return true;
                }
            },
            numLimit: {//图片上传张数限制
                type   : Number,
                default: 5,
            },
        },
        model  : {
            prop : 'value',
            event: 'change',
        },
        watch  : {
            value(newVal,oldVal){
                if (this.isMany) {
                    if(newVal.length !== this.$refs.upload.fileList.length){
                        for (let valIndex in newVal) {
                            this.$refs.upload.fileList.push({
                                url:newVal[valIndex],
                                status:'finished',
                            });
                        }
                    }
                } else {
                    this.checkUrlInUpload(newVal);
                }
            },
        },
        methods: {
            checkUrlInUpload(url){
                let isNoInUpload = true;
                for(let uploadIndex in this.$refs.upload.fileList){
                    let uploadInfo = this.$refs.upload.fileList[uploadIndex];
                    if(url === uploadInfo.url){
                        isNoInUpload = false;
                    }
                }
                if(isNoInUpload){
                    this.$refs.upload.fileList.push({
                        url:url,
                        status:'finished',
                    });
                }
            },
            handleView(url) {
                this.bigImgUrl = url;
                this.visible   = true;
            },
            handleRemove(file) {
                const fileList = this.$refs.upload.fileList;
                this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    
                !this.isMany && (this.uploadList = []);
                this.triggerValueUpdate();
               
            },
            handleSuccess(res, file) {
                file.url  = res.data.fileUrl;
                file.name = res.data.fileName;
                
                if(!this.isMany){
                    this.$emit('change', this.isOnlyUrl ? file.url : file);
                    this.uploadList = [];
                    this.uploadList.push(file);
                }else{
                    this.triggerValueUpdate();
                }
            },
            triggerValueUpdate(){
                
                //非多选，只留一张
                if (
                    !this.isMany
                    &&
                    this.$refs.upload.fileList.length > 1
                ) {
                    const fileList = this.$refs.upload.fileList;
                    this.$refs.upload.fileList.splice(this.$refs.upload.fileList.length - 1, 1);
                }
    
                let newVal = '';
                if (!this.isMany) {
                    if(this.$refs.upload.fileList.length){
                        newVal = this.$refs.upload.fileList[0];
    
                        newVal = this.isOnlyUrl ? newVal.url : newVal;
                    }else{
                        newVal = this.isOnlyUrl ? '' : null;
                    }
                } else {
                    newVal = this.$refs.upload.fileList;
        
                    if (this.isOnlyUrl) {
                        newVal = this.$refs.upload.fileList.map((val) => {
                            return val.url;
                        })
                    }
                }
    
                this.$emit('change', newVal)
            },
            handleFormatError(file) {
                this.$Notice.warning({
                    title: 'The file format is incorrect',
                    desc : 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
                });
            },
            handleMaxSize(file) {
                this.$Notice.warning({
                    title: 'Exceeding file size limit',
                    desc : 'File  ' + file.name + ' is too large, no more than 2M.'
                });
            },
            handleBeforeUpload() {
                const check = this.uploadList.length < this.numLimit;
                if (!check) {
                    this.$Notice.warning({
                        title: `最多只可上传 ${this.numLimit} 张图片`
                    });
                }
                return check;
            }
        },
        mounted() {
            this.uploadList = this.$refs.upload.fileList;
        }
    }
</script>
<style>
    .demo-upload-list {
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }
    
    .demo-upload-list img {
        width: 100%;
        height: 100%;
    }
    
    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }
    
    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }
    
    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>